<?php

namespace App\Repositories\Manage;

use App\Models\User\User;
use App\Models\User\UserRole;

class UserRepository
{

    /**
     * 获取用户角色
     * @param null $id
     */
    public function getRolesById($user_id = null, $type = false)
    {
        if (empty($user_id))
            return null;

        if ($type) {
            $field = "code";
        } else {
            $field = "role_id";
        }

        return UserRole::query()->where(['user_id' => $user_id])->pluck("role_id")->toArray();
    }

    /**
     * 获取用户角色Code
     * @param null $id
     */
    public function getRoleCodeByUsesrId($user_id = null)
    {
        return (new UserRole())
            ->setTable("ur")
            ->from("user_role as ur")
            ->join("role as r", "r.id", "=", "ur.role_id")
            ->where(['ur.user_id' => $user_id])
            ->pluck("r.code")
            ->toArray();
    }

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = User::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("nickname", "like", "%{$filter['keywords']}%");
            })
            ->select(['id', 'nickname', 'shop_id', 'username', 'mobile', 'avatar', 'bind_uid', 'status', 'update_time', 'create_time'])
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum);

        foreach ($res as $k => &$v) {
            $v['roleCodes'] = $v->roleCodes();
            $v['shop'] = $v->shop;
        }

        return filterPaginateData($res->toArray());
    }

    public function getOne($id = 0, $p = false)
    {
        $res = User::query()->where(['id' => intval($id)])->first();
        if (!$p && !empty($res)) {
            unset($res['password']);
            unset($res['salt']);
        }

        $res['roleIds'] = $res->roles();
        return $res;
    }

    /**
     * 检查是否是系统管理员
     * @param int $id
     */
    public function checkIsSuper(int $id = 0)
    {
        $code = (new UserRole())
            ->setTable("ur")
            ->from("user_role as ur")
            ->join("role as r", "r.id", "=", "ur.role_id")
            ->where(['ur.user_id' => $id])
            ->value("r.code");

        if (in_array($code, ['SUPER', 'ADMIN'])) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取
     * @param int $id
     * @return mixed
     */
    public function getShopIdById(int $id = 0)
    {
        return User::query()->where("id", $id)->value("shop_id");
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            User::where("id", $id)->update($data);
            return $id;
        } else {
            $data['salt'] = gen_salt(8);
            $data['password'] = genPassword("123456" . $data['salt']);
            $res = User::create($data);
            return $res['id'] ?? "";
        }

    }

    /**
     * 重置
     * @param int $id
     * @param null $password
     * @return bool
     */
    public function resetPassword($id = 0, $password = null)
    {
        if (empty($id) || empty($password)) {
            return false;
        }

        $salt = gen_salt(8);
        $password = genPassword($password . $salt);

        User::where("id", $id)->update([
            'password' => $password,
            'salt' => $salt
        ]);

        return true;
    }

    /**
     * 更新角色
     * @param int $user_id
     * @param array $role_id
     * @return bool
     */
    public function saveRoles($user_id = 0, $role_ids = [])
    {
        if (empty($role_ids))
            return true;
        UserRole::query()->where(['user_id' => $user_id])->delete();

        $data = [];
        foreach ($role_ids as $k => $role_id) {
            $data[] = [
                'user_id' => $user_id,
                'role_id' => $role_id,
                'create_time' => time(),
                'update_time' => time(),
            ];
        }

        UserRole::insert($data);
        return true;
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            User::where(['id' => $ids])->delete();
        } else {
            User::whereIn("id", $ids)->delete();
        }

        return retSuc([], "删除成功");
    }

}
